from flask import jsonify, request, render_template, session
from . import resource_bp
from utils.auth import login_required
import os
import json
from datetime import datetime
from werkzeug.utils import secure_filename
import random

@resource_bp.route('/', methods=['GET'])
@login_required
def index():
    """资源管理首页"""
    try:
        # 获取资源统计信息
        stats = get_resource_stats()
        
        # 获取文档列表
        data_file = os.path.join('workspace', 'data', 'documents.json')
        if os.path.exists(data_file):
            with open(data_file, 'r', encoding='utf-8') as f:
                docs = json.load(f)
                documents = []
                for doc in docs:
                    # 处理文件路径
                    file_path = doc.get('file_path', '')
                    if file_path:
                        # 确保路径格式正确
                        file_path = file_path.replace('\\', '/')  # 统一使用正斜杠
                        if file_path.startswith('static/'):
                            file_path = file_path[7:]  # 移除 static/ 前缀
                    
                    documents.append({
                        'id': doc['id'],
                        'text': doc['content'],
                        'uri': file_path,  # 这里的 file_path 应该是 'uploads/filename' 格式
                        'type': doc['tags'].get('type', 'other'),
                        'category': doc['tags'].get('category', ''),
                        'tags': doc['tags'].get('tags', []),
                        'created_at': doc['tags'].get('created_at', ''),
                    })
        else:
            documents = []
        
        return render_template('resource/index.html', 
                             username=session.get('username'),
                             documents=documents,
                             stats=stats)
    except Exception as e:
        print(f'加载文档列表错误: {str(e)}')
        import traceback
        print(traceback.format_exc())
        return render_template('resource/index.html', 
                             username=session.get('username'),
                             documents=[],
                             stats=get_resource_stats(),
                             error=str(e))

@resource_bp.route('/upload', methods=['POST'])
@login_required
def upload():
    try:
        resource_type = request.form.get('resource_type')
        description = request.form.get('description')
        category = request.form.get('category')
        tags = request.form.get('tags', '').split(',')
        tags = [tag.strip() for tag in tags if tag.strip()]

        # 创建基本文档数据
        doc_id = str(random.randint(1000000, 9999999))
        doc_data = {
            'id': doc_id,
            'content': description,
            'file_path': None,
            'tags': {
                'category': category,
                'type': resource_type,
                'tags': tags,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 格式化时间
            }
        }

        if resource_type == 'text':
            text_content = request.form.get('text_content')
            if not text_content:
                return jsonify({'status': 'error', 'message': '请输入文本内容'})
            doc_data['content'] = text_content
        else:
            if 'file' not in request.files:
                return jsonify({'status': 'error', 'message': '请选择文件'})
            
            file = request.files['file']
            if not file:
                return jsonify({'status': 'error', 'message': '无效的文件'})

            # 验证文件类型
            if resource_type == 'image' and not file.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                return jsonify({'status': 'error', 'message': '不支持的图片格式'})
            elif resource_type == 'video' and not file.filename.lower().endswith(('.mp4', '.webm')):
                return jsonify({'status': 'error', 'message': '不支持的视频格式'})

            # 保存文件
            original_filename = secure_filename(file.filename)
            filename_base, ext = os.path.splitext(original_filename)
            
            # 确保有正确的扩展名
            if not ext:
                if resource_type == 'image':
                    ext = '.jpg'
                elif resource_type == 'video':
                    ext = '.mp4'
            
            # 构建文件名：使用ID和扩展名
            filename = f"{doc_id}{ext}"
            
            # 构建路径
            file_path = f'uploads/{filename}'  # 数据库中存储的路径
            save_path = os.path.join('static', 'uploads', filename)  # 实际保存路径

            # 保存文件
            os.makedirs(os.path.dirname(save_path), exist_ok=True)
            file.save(save_path)
            
            # 保存文件路径
            doc_data['file_path'] = file_path
            doc_data['tags']['file_path'] = file_path

        # 保存到 documents.json
        data_file = os.path.join('workspace', 'data', 'documents.json')
        try:
            # 读取现有数据
            if os.path.exists(data_file):
                with open(data_file, 'r', encoding='utf-8') as f:
                    docs = json.load(f)
            else:
                docs = []

            # 添加新文档
            docs.append(doc_data)

            # 保存更新后的数据
            with open(data_file, 'w', encoding='utf-8') as f:
                json.dump(docs, f, ensure_ascii=False, indent=2)
            
            return jsonify({'status': 'success', 'message': '上传成功'})

        except Exception as e:
            print(f'保存到文件时出错: {str(e)}')
            import traceback
            print(traceback.format_exc())
            return jsonify({'status': 'error', 'message': str(e)})
    
    except Exception as e:
        print(f'上传错误: {str(e)}')
        import traceback
        print(traceback.format_exc())
        return jsonify({'status': 'error', 'message': str(e)})

@resource_bp.route('/api/documents/<doc_id>', methods=['DELETE'])
@login_required
def delete_document(doc_id):
    """删除文档"""
    try:
        data_file = os.path.join('workspace', 'data', 'documents.json')
        if os.path.exists(data_file):
            with open(data_file, 'r', encoding='utf-8') as f:
                docs = json.load(f)
            
            # 找到并删除文档
            docs = [doc for doc in docs if doc['id'] != doc_id]
            
            # 保存更新后的数据
            with open(data_file, 'w', encoding='utf-8') as f:
                json.dump(docs, f, ensure_ascii=False, indent=2)
            
            return jsonify({'status': 'success', 'message': '文档已删除'})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

def get_resource_stats():
    """获取资源统计信息"""
    try:
        data_file = os.path.join('workspace', 'data', 'documents.json')
        if not os.path.exists(data_file):
            return {
                'total_count': 0,
                'text_count': 0,
                'image_count': 0,
                'video_count': 0,
                'total_size': '0 B',
                'text_size': '0 B',
                'image_size': '0 B',
                'video_size': '0 B'
            }
            
        with open(data_file, 'r', encoding='utf-8') as f:
            docs = json.load(f)
            
        stats = {
            'total_count': len(docs),
            'text_count': 0,
            'image_count': 0,
            'video_count': 0,
            'text_size': 0,
            'image_size': 0,
            'video_size': 0
        }
        
        for doc in docs:
            doc_type = doc['tags'].get('type')
            if doc_type == 'text':
                stats['text_count'] += 1
                stats['text_size'] += len(doc.get('content', '').encode('utf-8'))
            elif doc_type == 'image':
                stats['image_count'] += 1
                file_path = os.path.join('static', doc.get('file_path', ''))
                if os.path.exists(file_path):
                    stats['image_size'] += os.path.getsize(file_path)
            elif doc_type == 'video':
                stats['video_count'] += 1
                file_path = os.path.join('static', doc.get('file_path', ''))
                if os.path.exists(file_path):
                    stats['video_size'] += os.path.getsize(file_path)
                    
        stats['total_size'] = stats['text_size'] + stats['image_size'] + stats['video_size']
        
        # 转换大小为可读格式
        for key in ['total_size', 'text_size', 'image_size', 'video_size']:
            stats[key] = format_size(stats[key])
            
        return stats
    except Exception as e:
        print(f"获取资源统计错误: {str(e)}")
        traceback.print_exc()
        return None

def format_size(size):
    """格式化文件大小"""
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size < 1024:
            return f"{size:.1f} {unit}"
        size /= 1024
    return f"{size:.1f} TB" 